package top.haijunit.common.response.advice;

import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;
import top.haijunit.common.response.data.RestResult;
import top.haijunit.common.response.api.ExcludeResponseWrapper;

import java.lang.reflect.Method;
import java.util.Objects;

/**
 * 非空返回值的处理
 *
 * @author zhanghaijun
 * @date 2024/6/6 13:18
 * @description [一句话描述该类的功能]
 */
@Slf4j
@ControllerAdvice(annotations = RestController.class)
public class GlobalRestResultWrapper implements ResponseBodyAdvice<Object> {

    /**
     * 只处理不返回void的，并且MappingJackson2HttpMessageConverter支持的类型.
     *
     * @param methodParameter 方法参数
     * @param clazz           处理器
     * @return 是否支持
     */
    @Override
    public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> clazz) {
        Method method = methodParameter.getMethod();
        if (Objects.isNull(method)
                || method.getReturnType().equals(Void.TYPE)
                || method.getReturnType().equals(RestResult.class)) {
            return false;
        }
        if (method.isAnnotationPresent(ExcludeResponseWrapper.class)) {
            return false;
        }
        if (method.getDeclaringClass().isAnnotationPresent(ExcludeResponseWrapper.class)) {
            return false;
        }
        if (method.getReturnType().isAnnotationPresent(ExcludeResponseWrapper.class)) {
            return false;
        }
        if (method.getDeclaringClass().getName().contains("springdoc")) {
            return false;
        }
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        if (returnType.getParameterType().isAssignableFrom(String.class)) {
            response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
            return JSONUtil.toJsonStr(RestResult.success(body));
        }
        if (returnType.getParameterType().isAssignableFrom(RestResult.class)) {
            return body;
        }
        return RestResult.success(body);
    }
}
